<?php

require_once(dirname(__DIR__) . '/api/DB.php');
require_once(dirname(__DIR__) . '/api/response.php');
require_once(dirname(__DIR__) . '/api/func.php');

$_PUT = [];
if ($_SERVER['REQUEST_METHOD'] === 'PUT') {
    // 读取原始输入数据
    $putData = file_get_contents('php://input');

    // 解析数据（如果是表单数据格式）
    parse_str($putData, $_PUT);
}

try {

    $db = new DB();
    $pdo = $db::$pdo;

    foreach (['article_id', 'title', 'category_id', 'content'] as $value) {

            if (!isset($_PUT[$value])) {
                throw new Exception(fieldMap($value) . '为必传项');
            };

            if (empty($_PUT[$value])) {
                throw new Exception(fieldMap($value) . '不能为空');
            }

    }

    // 判断文章是否存在
    $sql = 'select * from articles where id = ?';
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$_PUT['article_id']]);
    $res = $stmt->fetch(PDO::FETCH_ASSOC);
    if (empty($res)) {
        throw new Exception('文章不存在');
    }

    // 查询分类
    $sql = 'select * from categories where id = ?';
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$_PUT['category_id']]);
    $categoryName = $stmt->fetch(PDO::FETCH_ASSOC)['name'];

    // 更新
    $sql = 'update articles set title = ?, category = ?, category_id = ?, content = ? where id = ?';
    $stmt = $pdo->prepare($sql);
    $res = $stmt->execute([$_PUT['title'], $categoryName, $_PUT['category_id'], $_PUT['content'], $_PUT['article_id']]);
    if (empty($res)) {
        throw new Exception('更新失败');
    }

    myResponse('', 1, 200);
} catch (Exception $e) {
    myResponse($e->getMessage(), 0, 200);
}